package com.lagou.util;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class CmdUtil {

    private static Logger logger = LoggerFactory.getLogger(CmdUtil.class);

    public static void command(String command){
        try {
            Process process = Runtime.getRuntime().exec(command);
            String inStr = consumeInputStream(process.getInputStream());
            String errStr = consumeInputStream(process.getErrorStream());
            if (inStr != null && inStr.length() != 0) {
                logger.info("执行结果:" + inStr);
            }
            if (errStr != null && errStr.length() != 0) {
                logger.info("执行结果:" + errStr);
            }
        } catch (Exception e) {
            logger.error("执行cmd命令失败:", e);
        }
    }

    private static String consumeInputStream(InputStream is) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(is,"GBK"));
        String s;
        StringBuilder stringBuilder = new StringBuilder();
        while ((s = br.readLine()) != null) {
            stringBuilder.append("\r\n").append(s);
        }
        return stringBuilder.toString();
    }

    @Test
    public void ipconfig() {
        CmdUtil.command("ipconfig");
    }

    @Test
    public void binarySearch() {
        CmdUtil.command("java -version");
    }
}
